﻿using System;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace VS2012_MSHA_Helper
{
    enum MshaType
    {
        Group,
        Book,
        Package
    }

    public partial class Main : Form
    {
        private MshaBookGroups _groups;

        private void DisplayMessage(string message)
        {
            stsLbl.Text = message;
        }

        private void ShowBook(MshaBookGroup group)
        {
            lvPackages.BeginUpdate();
            lvPackages.Items.Clear();
            if (group != null)
            {
                foreach (MshaBook book in group)
                {
                    var item = lvPackages.Items.Add(book.Name);
                    item.ImageIndex = 0;
                    item.Tag = book;
                }
            }
            lvPackages.EndUpdate();
        }

        private void ShowPackage(MshaBook book)
        {
            lvPackages.BeginUpdate();
            lvPackages.Items.Clear();
            if (book != null)
            {
                foreach (MshaPackage package in book)
                {
                    var item = lvPackages.Items.Add(package.Name);
                    item.ImageIndex = 0;
                    item.Tag = package;
                }                
            }
            lvPackages.EndUpdate();
        }

        private void ShowDetail(ListViewItem item,bool expandTree = false)
        {
            if (item == null)
            {
                pnlConver.BringToFront();
                return;
            }
            if (item.Tag is MshaBook)
            {
                if (expandTree)
                {
                    var treeNode = (item.Tag as MshaBook).Tag as TreeNode;
                    if (treeNode != null)
                        treeNode.Parent.Expand();
                    tvBooks.SelectedNode = treeNode;
                    ShowPackage(item.Tag as MshaBook);
                }
                else
                {
                    ShowBookDetail(item.Tag as MshaBook);
                }
            }
            else if (item.Tag is MshaPackage)
            {
                ShowPackageDetail(item.Tag as MshaPackage);
            }
        }

        private void ShowPackageDetail(MshaPackage package)
        {
            SetHeight(MshaType.Package);
            ClearMessage();
            if (package == null) return;
            lblPkgType.Text = package.PackageType;
            lblPkgFormat.Text = package.PackageFormat;
            lblPkgDeplyed.Text = package.Deployed;
            lblPkgEtag.Text = package.Etag;
            lblPkgModifyTime.Text = package.LastModified;
            lblPkgLink.Text = package.CurrentLink;
            lblPkgLink2.Text = package.ConstituentLink;
            lblPkgName.Text = package.Name;
            lblPkgSize.Text = package.PackageSize;
            lblPkgUncompressed.Text = package.UncompressedSize;
            pnlPackage.BringToFront();
        }

        private void ShowBookDetail(MshaBook book)
        {
            SetHeight(MshaType.Book);
            ClearMessage();
            if (book == null) return;
            lblBookid.Text = book.Id;
            lblBookLocal.Text = book.Locale;
            lblBookName.Text = book.Name;
            lblBookDesciption.Text = book.Description;
            lblBookPackageName.Text = book.BrandingPackageName;
            pnlBook.BringToFront();
        }

        private void ShowGroupDetail(MshaBookGroup group)
        {
            SetHeight(MshaType.Group);
            ClearMessage();
            if (group == null) return;
            lblBookGroupId.Text = group.Id;
            lblBookGroupName.Text = group.Name;
            lblBookGroupVendor.Text = group.Vendor;
            pnlBookGroup.BringToFront();
        }

        private void ClearMessage()
        {
            foreach (Panel pnl in splitContainer3.Panel2.Controls)
            {
                foreach (var ctrl in pnl.Controls)
                {
                    if ((ctrl is Label) && ((ctrl as Label).Name.StartsWith("lbl")))
                    {
                        (ctrl as Label).Text = "";
                    }
                }  
                pnl.SendToBack();
            }
            pnlConver.BringToFront();
        }

        private void SetHeight(MshaType type)
        {
            var hight = 161;
            switch (type)
            {
                case MshaType.Group:
                    hight = 93;
                    break;
                case MshaType.Book:
                    hight = 140;
                    break;
                case MshaType.Package:
                    hight = 161;
                    break;
            }
            splitContainer3.SplitterDistance = splitContainer3.Height - hight;
        }

        private void LabelClick(object sender, EventArgs e)
        {
            if (sender is Label)
                DisplayMessage("   " +(sender as Label).Text);
        }

        private void SetLabelClickAction()
        {
            foreach (Panel pnl in splitContainer3.Panel2.Controls)
            {
                foreach (var ctrl in pnl.Controls)
                {
                    if ((ctrl is Label) && ((ctrl as Label).Name.StartsWith("lbl")))
                    {
                        (ctrl as Label).Click += LabelClick;
                    }
                }  
            }            
        }

        public Main()
        {
            InitializeComponent();
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            //CursorObject(object control)
            Cursor = Cursors.WaitCursor;
            DisplayMessage("准备下载");
            var request = WebRequest.Create(txtUrl.Text) as HttpWebRequest;
            if (request != null)
            {
                request.KeepAlive = false;
                using (var response = request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        var hp = new HtmlParser();
                        hp.LoadFromStream(stream);
                        _groups = hp.Action();
                        tvBooks.BeginUpdate();
                        tvBooks.Nodes.Clear();
                        foreach (MshaBookGroup bookGroup in _groups)
                        {
                            var groupNode = tvBooks.Nodes.Add(bookGroup.Name);
                            groupNode.Tag = bookGroup;
                            foreach (MshaBook book in bookGroup)
                            {
                                var bookNode = groupNode.Nodes.Add(book.Name);
                                bookNode.Tag = book;
                                book.Tag = bookNode;
                            }
                        }
                        tvBooks.EndUpdate();
                    }
                }
                request.Abort();
            }
            Cursor = Cursors.Default;
        }

        private void btnMake_Click(object sender, EventArgs e)
        {
            var brower = new FolderBrowserDialog();
            if (brower.ShowDialog() != DialogResult.OK) return;
            MshaBuilder.SaveFolder = brower.SelectedPath;
            Cursor = Cursors.WaitCursor;
            buildProcess.Visible = true;
            buildProcess.Maximum = _groups.Count;
            for (var i = 0; i < _groups.Count; i++)
            {
                MshaBuilder.Build(_groups[i]);
                buildProcess.Value = i;
            }
            buildProcess.Visible = false;
            Cursor = Cursors.Default;
            DisplayMessage("msha文件制做完成.");
        }

        private void tvBooks_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node == null) return;
            var node = e.Node;
            if (node.Tag is MshaBookGroup)
            {
                ShowBook(node.Tag as MshaBookGroup);
                ShowGroupDetail(node.Tag as MshaBookGroup);
            }
            else if (node.Tag is MshaBook)
            {
                ShowPackage(node.Tag as MshaBook);
                ShowBookDetail(node.Tag as MshaBook);
            }
        }

        private void lvPackages_MouseClick(object sender, MouseEventArgs e)
        {
            var item = lvPackages.GetItemAt(e.X, e.Y);
            ShowDetail(item);
        }

        private void lvPackages_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var item = lvPackages.GetItemAt(e.X, e.Y);
            ShowDetail(item,true);

        }

        private void Main_Load(object sender, EventArgs e)
        {
            SetLabelClickAction();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var urls = new StringBuilder();
            foreach (MshaBookGroup bookGroup in _groups)
            {
                foreach (MshaBook book in bookGroup)
                {
                    foreach (MshaPackage package in book)
                    {
                        urls.Append(package.CurrentLink + Environment.NewLine);
                    }
                }
            }
            var data = urls.ToString();
            Clipboard.SetText(data);
            DisplayMessage("拷贝完成.");
        }
    }
}
